type MessageHandler<T = any> = (payload: T) => void;

class BoardChannel<T extends string = string> {
  private channel: BroadcastChannel;
  private callbacks: Map<string | '*', MessageHandler>;

  constructor(channelName: string) {
    this.channel = new BroadcastChannel(channelName);
    this.callbacks = new Map();
    this.channel.addEventListener('message', this.handleMessage.bind(this));
  }

  private handleMessage(event: MessageEvent<{ type: T; payload: any }>) {
    const { type, payload } = event.data;
    
    if (this.callbacks.has(type)) {
      this.callbacks.get(type)!(payload);
    } else if (this.callbacks.has('*')) {
      this.callbacks.get('*')!(event.data);
    }
  }

  send<P = any>(type: T, payload: P): void {
    this.channel.postMessage({ type, payload });
  }

  on<P = any>(type: T | '*', callback: MessageHandler<P>): void {
    this.callbacks.set(type, callback);
  }

  off(type: T | '*'): void {
    this.callbacks.delete(type);
  }

  close(): void {
    this.channel.close();
    this.callbacks.clear();
  }
}

export default BoardChannel;